import Taro from '@tarojs/taro';
import { makeAutoObservable, runInAction } from 'mobx';
import { userType } from '@/types'
import http from '@/request'
import viewMode from './viewMode';

const localData = Taro.getStorageSync('user-info') as userType | null
// const localData = { userName: '', id: 0 }

class Store {
  // 是否通过检查（如果开启身份验证后需要校验）
  isChecked: false
  info: userType | null = localData?.id ? localData : {
    userName: '',
    avatarUrl: '',
    token: '',
    phone: '',
    createTime: ''
  };
  updateInfo = (data?: userType) => {
    if (data) {
      return new Promise(resolve => {
        Taro.setStorageSync('user-info',data)
        this.info = data;
        resolve(true)
      })
    } else {
      return http.get('/user/info').then(res => {
        Taro.setStorageSync('user-info',res.data)
        runInAction(() => {
          this.info = { ...res.data };
        })
      })
    }
  }
  checkUserAuth = (title, force = false) => {
    return new Promise((resolve, reject) => {
      viewMode.setIsIdentityCheckWait(true)
      if (this.info?.identityCheck || force) {
        Taro.checkIsSupportSoterAuthentication({
            success(res) {
                const supportMode = res.supportMode || []
                if (!supportMode.length) {
                    reject({msg: '该设备不支持生物识别，请在其他设备上使用'})
                    return
                }
                Taro.startSoterAuthentication({
                    requestAuthModes: res.supportMode,
                    challenge: 'ai-ledger-taro',
                    authContent: title,
                    success() {
                      viewMode.setIsIdentityCheckWait(false)
                        resolve(true)
                    },
                    fail(){
                        reject({msg: '取消验证'})
                    },
                    complete(res) {
                      console.log(res);
                      
                    }
                })
            },
            fail(){
              reject({msg: '该设备不支持生物识别，请在其他设备上使用'})
            }
        })
      } else {
        // 不强制校验时，当identityCheck设置为0时不校验
        resolve(true)
        viewMode.setIsIdentityCheckWait(false)
      }
    })
  }
  constructor() {
    makeAutoObservable(this);
  }
}

export default new Store();
